//
//  BUPangleAdTools.m
//  速睡
//
//  Created by 王亮 on 2020/10/26.
//  Copyright © 2020 shushui. All rights reserved.
//

#import "BUPangleAdTools.h"
#import <BUAdSDK/BUAdSDK.h>

#import "CJXPermissionsManage.h"
#import "NSDate+Extension.h"
#import "AppDelegate.h"

/** 穿山甲key */
#define AdAppID @"5159460"
//开屏广告
#define SplashAdID @"887458943"
//插屏广告
#define SlugAdID @"945998969"
//激励视频
#define InitiateVideoAdID @"945998973"


static BUPangleAdTools *class = nil;

@interface BUPangleAdTools () <BUSplashAdDelegate,BUNativeExpressRewardedVideoAdDelegate,BUNativeExpresInterstitialAdDelegate>{

}
/** 开屏广告 */
@property(nonatomic,strong) BUSplashAdView *splashAdView;
/** 插屏广告 */
@property(nonatomic,strong) BUNativeExpressInterstitialAd *interstitialAd;
/** 激励视频 */
@property(nonatomic,strong) BUNativeExpressRewardedVideoAd *nativeExpressRewardedVideoAd;



@end



@implementation BUPangleAdTools
#pragma mark -- 单利方法重写 --
//+ (id)allocWithZone:(struct _NSZone *)zone{
//    if (!class) {
//        class = [super allocWithZone:zone];//如果没有实例让父类去创建一个
//        return class;
//    }
//    return nil;
//}
//- (id)copyWithZone:(struct _NSZone *)zone{
//    return self;
//}
+ (instancetype) singletonMod {
    @synchronized(self) {
        if (class == nil) {
            class = [[self alloc] init];
        }
    }
    return class;
}




- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}

-(void)initData{
    //穿山甲
    [BUAdSDKManager setAppID:AdAppID];
    [BUAdSDKManager setIsPaidApp:NO];
#if DEBUG
    [BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
#else
    [BUAdSDKManager setLoglevel:BUAdSDKLogLevelNone];
#endif
}

#pragma -- mark -- 开屏广告
/**
 开屏广告
 */
- (void)showOpenAd{
    //内购用户无广告
//    if ([[DLStore singletonMod] dl_isSubscribedWithAutoRenewProduct]){
    [self clossAd];
    return;
//    }
    /** 默认延迟 关闭广告页 加载成功则取消 */
    [self reloadClossAd];
    [self getIDFAPermissions:^{
        /** 穿山甲 */
        [self.splashAdView loadAdData];
        /** 默认延迟 关闭广告页 加载成功则取消 */
        [self reloadClossAd];
    }];
}

#pragma mark - 穿山甲开屏广告 代理
- (void)splashAdDidLoad:(id)splashAd{
    NSLog(@"广告成功加载");
    BUSplashAdView *ad = splashAd;
    ad.rootViewController = self.rootViewController;
    [self.showAdView addSubview:ad];
    /** 广告成功加载则取消默认的自动关闭 */
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(clossAd) object:@"clossAd"];
}
- (void)splashAd:(BUSplashAdView *)splashAd didFailWithError:(NSError * _Nullable)error{
    if (error){
        [self clossAd];
    }
}
//此回调在广告跳转到其他控制器时，该控制器被关闭时调用。interactionType：此参数可区分是打开的appstore/网页/视频广告详情页面
- (void)splashAdDidCloseOtherController:(BUSplashAdView *)splashAd interactionType:(BUInteractionType)interactionType{
    NSLog(@"移除广告");
    [splashAd removeFromSuperview];
    [self clossAd];
}
//用户点击跳过按钮时会触发此回调，可在此回调方法中处理用户点击跳转后的相关逻辑
- (void)splashAdDidClickSkip:(BUSplashAdView *)splashAd {
    NSLog(@"移除广告");
    [splashAd removeFromSuperview];
    [self clossAd];
}
//倒计时为0时会触发此回调，如果客户端使用了此回调方法，建议在此回调方法中进行广告的移除操作
- (void)splashAdCountdownToZero:(BUSplashAdView *)splashAd {
    NSLog(@"移除广告");
    [splashAd removeFromSuperview];
    [self clossAd];
}


#pragma mark -- 插屏广告
/** 展示插屏广告 */
-(void)showSlugAdBlock:(initSlugAdEndBlock)initSlugAdEndBlock FromVc:(UIViewController *)fromVc{
    self.rootViewController = fromVc;
    [self.interstitialAd loadAdData];
}
/** 渲染成功回调 */
- (void)nativeExpresInterstitialAdRenderSuccess:(BUNativeExpressInterstitialAd *)interstitialAd{
    if (self.interstitialAd) {
       [self.interstitialAd showAdFromRootViewController:self.rootViewController];
    }
}
#pragma mark -- 激励视频
/** 展示激励视频 */
-(void)showInitiateVideoAdBlock:(initInitiateVideoAdEndBlock)initInitiateVideoAdEndBlock FromVc:(UIViewController *)fromVc{
    self.rootViewController = fromVc;
    self.initInitiateVideoAdEndBlock = initInitiateVideoAdEndBlock;
    [self.nativeExpressRewardedVideoAd loadAdData];
}
/** 此回调方法中可定位具体的失败原因对应的错误码，打印error即可。所有错误码详情请见链接。Link */
- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error{
    if (self.initInitiateVideoAdEndBlock){
        self.initInitiateVideoAdEndBlock(Ad_Close_Type_Error);
    }
}
/** 建议在此回调方法中进行广告的展示操作，可保证播放流畅和展示流畅，用户体验更好。 */
- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    if (self.nativeExpressRewardedVideoAd) {
        [self.nativeExpressRewardedVideoAd showAdFromRootViewController:self.rootViewController];
    }
}
/** 渲染失败，网络原因或者硬件原因导致渲染失败,可以更换手机或者网络环境测试。建议升级到穿山甲平台最新版本 */
- (void)nativeExpressRewardedVideoAdViewRenderFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error{
    if (self.initInitiateVideoAdEndBlock){
        self.initInitiateVideoAdEndBlock(Ad_Close_Type_Error);
    }
}
/** 用户关闭广告时会触发此回调，注意：任何广告的关闭操作必须用户主动触发; */
- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd{
    _nativeExpressRewardedVideoAd = nil;
}
/** 异步请求的服务器验证成功回调，开发者需要在此回调中进行奖励发放。现在包括两个验证方法:1. C2C需要服务器验证2。S2S不需要服务器验证。 */
- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify{
    if (self.initInitiateVideoAdEndBlock){
        self.initInitiateVideoAdEndBlock(Ad_Close_Type_Sure);
    }
}
/** 异步请求的服务器验证失败回调。可在此回调方法中打印error，定位具体失败的原因，或通过抓包定位具体原因 */
- (void)nativeExpressRewardedVideoAdServerRewardDidFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error{
    if (self.initInitiateVideoAdEndBlock){
        self.initInitiateVideoAdEndBlock(Ad_Close_Type_Error);
    }
}


#pragma mark -- 关闭回调
/** Block */
-(void)setAdEndBlock:(initAdEndBlock)initAdEndBlock{
    self.initAdEndBlock = initAdEndBlock;
}
/** 重置内置的开屏关闭管理 */
-(void)reloadClossAd{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(clossAd) object:@"clossAd"];
    [self performSelector:@selector(clossAd) withObject:@"clossAd" afterDelay:3.f];
}
-(void)clossAd{
    /** 广告成功加载则取消默认的自动关闭 */
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(clossAd) object:@"clossAd"];
    if (self.initAdEndBlock){
        self.initAdEndBlock(Ad_Close_Type_Normal);
    }
}



#pragma -- mark --权限请求
-(void)getIDFAPermissions:(void(^)(void))block{
    [[CJXPermissionsManage sharedInstance] getIDFAPermissions:^(BOOL authorized, NSString *idfa) {
        NSLog(@"状态：%@ - idfa：%@",authorized?@"开启":@"关闭",idfa);
        if (block){
            block();
        }
    }];
}

#pragma mark -- APP 后台重启展示广告逻辑
/** App 进入后台 */
-(void)AdAppBackground{
    self.backgroundDate = [NSDate new];
}
/** App 进入前台 */
-(void)AdAppShow{
    if (!self.backgroundDate){return;}
    NSInteger diff = [[NSDate new] timeIntervalSince1970] - [self.backgroundDate timeIntervalSince1970];
    if (diff > 30){
        self.rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        self.showAdView = self.rootViewController.view;
        [self showOpenAd];
    }
}

#pragma -- mark 懒加载
-(BUSplashAdView *)splashAdView{
    if (!_splashAdView){
        CGRect frame = [UIScreen mainScreen].bounds;
        _splashAdView = [[BUSplashAdView alloc] initWithSlotID:SplashAdID frame:frame];
        _splashAdView.delegate = self;
    }
    return _splashAdView;
}
-(BUNativeExpressInterstitialAd *)interstitialAd{
    if (!_interstitialAd){
        CGFloat w = Main_Screen_Width  - 80;
        CGFloat h = w * 1.5f;
        _interstitialAd = [[BUNativeExpressInterstitialAd alloc] initWithSlotID:SlugAdID adSize:CGSizeMake(w,h)];
        _interstitialAd.delegate = self;
    }
    return _interstitialAd;
}
-(BUNativeExpressRewardedVideoAd *)nativeExpressRewardedVideoAd{
    if (!_nativeExpressRewardedVideoAd){
        BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
        model.userId = [UserModel_WL xid];
        _nativeExpressRewardedVideoAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:InitiateVideoAdID rewardedVideoModel:model];
        _nativeExpressRewardedVideoAd.delegate = self;
    }
    return _nativeExpressRewardedVideoAd;
}
@end
